<?php
/**
 * Create a new Inquiry
 */

use Fox\SalesDistribution\Sales;
use Fox\Message;
use Fox\Dao\SqlFragment;
use Fox\SalesDistribution\Sales\Partner\Role;
use Fox\SalesDistribution\Sales\Inquiry\Partner;
use Fox\Common\Customer;
use Fox\SalesDistribution\Sales\Inquiry;
use Fox\Html\Screen;
$screen = new Screen("eInquiry","create");
$screen->mainTitle("Nouvelle Offre");//@TODO Transalte
$blHeader = Xview::instance()->component("inquiry", "header");
$screen->add($blHeader);
$blItems = Xview::instance()->component("inquiry", "items");
$screen->add($blItems);
$blCustomer = Xview::instance()->component("inquiry", "customer");
$screen->add($blCustomer);
$blResponsible = Xview::instance()->component("inquiry", "responsible");
$screen->add($blResponsible);
$blCompetitors = Xview::instance()->component("inquiry", "competitors");
$screen->add($blCompetitors);
if($screen->submitted())
{
	$inquiry = new Inquiry();
	$inquiryType = $blHeader->item("type")->get();
	// Make Optionnal Field Mandatory
	if(!empty($inquiryType) && ( $inquiryType == Inquiry::TYPE_PRIVATE
							  || $inquiryType == Inquiry::TYPE_LIMITATED) )
	{
		$blCustomer->item("street")->mandatory();
		$blCustomer->item("postal_code")->mandatory();
		$blCustomer->item("city")->mandatory();
		$blCustomer->item("phone1")->mandatory();
		$blCustomer->item("email1")->mandatory();
		$blCustomer->item("contact")->mandatory();
	}

	$inputs = $screen->get();
	if(count($inputs['gItems']) == 0)
	{
		Fox\Message::Error(Msg(Sales::BUNDLE_NAME,22));
	}
	else
	{
		$total = 0;
		$root = new Fox\Node(Fox\Node::ROOT_NODE);
		foreach($inputs['gItems'] as $line)
		{
			if(!isset($line['materialid']))
				continue;

			if(isset($treeData[$line['parentid']]))
			{
				$treeData[$line['materialid']] = $treeData[$line['parentid']]->add(new Fox\Node($line));
			}
			else
			{
				$treeData[$line['materialid']] = $root->add(new Fox\Node($line));
			}
			// Pick Node without total
			if(empty($line['amount_initial']))
			{
				$nodeToBeChecked[] = $treeData[$line['materialid']];
			}

			// Build Items
			$item = new Inquiry\Item();
			$item->setFields($line);
			$inquiry->item($item);
			$total += $line['amount_initial'];
		}
		$blItems->item("gItems")->initialize($root,true);
		if($total == 0)
		{
			Fox\Message::Error(Msg(Sales::BUNDLE_NAME,23));
		}
		if(isset($nodeToBeChecked))
		{
			foreach($nodeToBeChecked as $node)
			{
				/* @var $node Fox\Node */
				if($node->getChildrenCount() > 0)
				{
					continue;
				}
				else
				{
					Fox\Message::Error(Msg(Sales::BUNDLE_NAME,93,$node->getProperty("label")));
				}
			}
		}
	}
	if(!$screen->errors())
	{
		// Check Unicity of the Reference
		$finder = new Inquiry();
		$res = $finder->find(new SqlFragment("reference = ?",array($inputs['reference'])));
		if(count($res) > 0)
		{
			Message::Error(Msg(Sales::BUNDLE_NAME,Sales::MSG_DUPLICATE_INQUIRY,$inputs['reference']));
		}
	}


	if(!$screen->errors())
	{
		$customerData = $blCustomer->get();
		unset($customerData['customerid']);
		$contactData = $customerData;
		$customerData['name1'] = $inputs['customername'];
		$contactData['name1'] = $inputs['contact'];
		$contactData['type'] = Fox\Common\Customer::TYPE_CONTACT;

		try {
			// Manage Customer
			$customer = new Customer($inputs['customerid']);
			$keyname = Fox\Utilities::cleanup($inputs['customername']);
			if($customer->exists())
			{
				if($customer->keyname != $keyname)
				{
					$customer = new Customer();
					$customer->setFields($customerData);
				}
			}
			// Check if the customer does not exist in the database
			if(!$customer->exists())
			{
				// Check if the same customer exist
				$finder = new Customer();
				$keyname = Fox\Utilities::cleanup($inputs['customername']);
				$res = $finder->find(new Fox\Dao\SqlFragment("keyname = ?",array($keyname)));
				if(count($res) > 0)
				{
					$customer = $res[0];
				}
			}
			// Manage Customer adress changes
			$contact = new Customer($inputs['contactid']);

			$keyname = Fox\Utilities::cleanup($inputs['contact']);
			if($contact->exists())
			{
				if($contact->keyname != $keyname)
				{
					$contact = new Customer();
					$contact->setFields($contactData);
				}
			}
			$contact->setFields($contactData);
			if(!$contact->exists() && $customer->exists())
			{
				// Need to check if this contact is not already in the
				// partners list of the customer
				$contact = $customer->isPartner($contact);
			}
			// Create the customer
			if(!$customer->exists())
			{
				$customer->setFields($customerData);
				$customer->setFields(array("type" => Customer::TYPE_PROSPECT));
				$customer->create();
			}
			// Create the contact
			if(!$contact->exists() && !empty($contactData['name1']))
			{
				$contact->create();
				$partner = new Fox\Common\Customer\Partner();
				$partnerData['role'] = Role::CONTACT_PERSON;
				$partnerData['partnerid'] = $contact->getId();
				$partnerData['defaultflag'] = 0;
				$partnerData['customerid'] = $customer->getId();
				$partner->setFields($partnerData);
				$customer->partner($partner);

			}
			$customer->prepareUpdate(Customer::CHANGE_SALES);
			$customer->update();


			$inquiry->setFields($inputs);
			// Add Competitors to the Inquiry
			$competitors = $blCompetitors->item("gCompetitors")->get(null,true);
			foreach($competitors as $competitor)
			{
				$partner = new Partner();
				$partner->role = Role::COMPETITOR;
				$partner->setFields(array("customerid" => $competitor['customerid'],
											"role" => Role::COMPETITOR,
											"itemid" => 0));
				$inquiry->partners($partner);
			}

			// Add Operationnal Entity
			$opEntities = $blResponsible->item("op_entity")->default;
			if(is_array($opEntities))
			{
				foreach($opEntities as $partnerid => $value)
				{
					$partner = new Partner();
					$partner->role = Role::OPERATIONAL_ENTITY;
					$partner->setFields(array("customerid" => $partnerid,
													"role" => Role::OPERATIONAL_ENTITY,
													"itemid" => 0));
					$inquiry->partners($partner);
				}
			}

			// Add Customer
			$inquiry->partners($customer,Role::SOLD_TO_PARTY);
			$inquiry->customerid = $customer->customerid;
			// Add contact
			if(isset($contact) && $contact->exists())
			{
				$inquiry->partners($contact,Role::CONTACT_PERSON);
			}
			// Responsible Entity
			try {
				$responsible = new Customer($inputs['agency']);
				$inquiry->partners($responsible,Role::RESPONSIBLE_AGENCY);
			}
			catch (Fox\Object\Exception\NotExist $e)
			{
				// Do nothing -> should not be possible
			}

			// Responsible Entity
			try {
				$person = new Customer($inputs['sourceid']);
				$inquiry->partners($person,Role::RESPONSIBLE_PERSON);
			}
			catch (Fox\Object\Exception\NotExist $e)
			{
				// Do nothing -> should not be possible
			}
		 	$inquiry->status = Inquiry::STATUS_WIP;
			$inquiry->create();

			$id = $inquiry->getId();
			Fox\Message::Success(Msg(Sales::BUNDLE_NAME,24,$id));
			Xview::instance()->redirect("?mod=inquiry&act=update&inquiryid=$id");
		}
		catch(Fox\Object\Exception\Save $e)
		{
			var_dump($e);
			Fox\Core\Errors::pushMessage($e);
		}
		catch (Fox\Object\Exception\NotExist $e)
		{
			Fox\Message::Error($e->getMessage());
		}
		catch (Exception $e)
		{
			var_dump($e);
			Fox\Message::Error($e->getMessage());
		}
	}
}
echo $screen->Display();